# -*- coding:utf-8 -*-
# @Time : 21-8-10 下午3:14 
# @Author : zdy
# @File : LSFit.py
# desc:
from Class.Factor import Factor
class Fit(object):
    @staticmethod
    def LineFit(x,y,through=False):
        p=[None,None]
        length=len(x)
        xx=0.0
        yy=0.0
        s1=0
        s2=0
        if through:
            xx=0
            yy=0
        else:
            xx= Factor.calculateAverage(x)
            yy= Factor.calculateAverage(y)
        for i in range(length):
            s1+=(x[i] -xx)*(y[i]-yy)
            s2+=(x[i]-xx)*(x[i]-xx)
        p[0]=s1/s2
        p[1]=yy-p[0]*xx
        return p

    @staticmethod
    def Coefficient(x, y):
        s1 = s2 = s3 = 0.0
        # 计算平均值
        x_ = Factor.calculateAverage(x)
        y_ = Factor.calculateAverage(y)
        # 循环读取每个值，计算对应值的累和
        for i in range(len(x)):
            s1 += (x[i] - x_) * (y[i] - y_)
            s2 += (x[i] - x_) ** 2
            s3 += (y[i] - y_) ** 2
        # 计算相关系数
        try:
            # r = s1 / ((s2 ** 0.5) * (s3 ** 0.5))
            r = s1 / ((s2 *s3)** 0.5)
        except Exception as ex:
            return 0
        return r

